﻿using System;
using System.IO;
using System.Reflection;

namespace AppConfigVerifier
{
	public class IncludeExcludeAssemblyRule : Rule
	{
		public IncludeExcludeAssemblyRule(AssemblyName assembly, bool include)
		{
			if(assembly == null)
			{
				throw new ArgumentNullException("assembly");
			}
			assemblyName = assembly;
			this.include = include;
		}

		readonly bool include;
		readonly AssemblyName assemblyName;

		public override void Apply(LocalContext context)
		{
			TypeDefinition typeDefinition;
			try
			{
				typeDefinition = Utility.GetTypeDefinition(context.TypeName);
			}
			catch(FileLoadException)
			{
				context.Log.Send("Cannot parse assembly name in "
					+ context.TypeName, LogType.Error);
				return;
			}

			if(typeDefinition.AssemblyName == null)
			{
				return;
			}

			if(typeDefinition.AssemblyName.IsSubsetOf(assemblyName).Success)
			{
				context.GetExtension<InclusionExclusionExtension>().IsIncluded = include;
			}
		}
	}
}
